//this file is part of ePopup
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "StdAfx.h"
#include "PopupClientThread.h"
#include "popup.h"
#include "popupdlg.h"
//#include "UserMsgs.h"
#include "OtherFunctions.h"
#include "TaskbarNotifier.h"
#include "ResourceEntry.h"
#include "SenderDialog.h"
#include "PopupClient.h"
#include <vector>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

using namespace std;

/////////////////////////////////////////////////////////////////////////////////////////
///PopupClientThread
IMPLEMENT_DYNCREATE(PopupClientThread, CWinThread)

PopupClientThread::PopupClientThread() 
 : m_popupapp((CpopupApp*) AfxGetApp()), 
   m_popupdlg(m_popupapp->popupdlg),
   m_resources(m_popupapp->m_resources),
   m_options(m_popupapp->m_options),
   m_logger(m_popupapp->m_logger)
{
}

BOOL PopupClientThread::InitInstance()
{
	return TRUE;
}

int PopupClientThread::Run()
{
	m_popupdlg->ShowWindow(SW_HIDE);

	while (true)
	{	
		CSingleLock _lock(&CpopupApp::s_clientmutex);
		_lock.Lock();
		m_popupapp->m_popupclient = new PopupClient (m_popupapp->m_servername,
													 m_popupapp->m_serverport,
													 MFCStringToSTLString(m_popupapp->m_username),
													 (PopupClientUI*) m_popupdlg,
													 &(m_popupdlg->m_mode));
		_lock.Unlock();

		m_logger << "connecting to server" << endl;
		m_logger.flush();

		// Starting main routine (blocking call, until disconnection)
		m_popupapp->m_popupclient->run();

		_lock.Lock();
		m_popupdlg->clearClients();
		delete m_popupapp->m_popupclient;
		m_popupapp->m_popupclient = 0;

		_lock.Unlock();

		Sleep (5000);
	}

	m_logger << " - Main thread exited" << endl;
	m_logger.flush();

	return 0;
}

void PopupClientThread::kill()
{
	AfxEndThread(0);
}
